package controllers

import (
	"github.com/gin-gonic/gin"
	"github.com/globalsign/mgo/bson"
)

type UserAddrQuery struct {
	BaseRequest
	Uid       string `form:"uid"`
	Name      string `form:"name"`
	TimeOrder int    `form:"timeOrder"`
	StartTime int64  `form:"startTime"`
	EndTime   int64  `form:"endTime"`
}

func GetUserAddrList(c *gin.Context) {
	q := &UserAddrQuery{}
	if err := c.ShouldBindQuery(&q); err != nil {
		handleErr(c, 404, err.Error())
		return
	}

	mquery := make(map[string]interface{}, 0)
	if q.Uid != "" {
		mquery["uid"] = q.Uid
	}
	if q.Name != "" {
		mquery["name"] = q.Name
	}

	if q.Uid != "" || q.Name != "" {
		orderList := []string{"-time"}
		if q.TimeOrder == 1 {
			orderList = []string{"time"}
		}

		if q.StartTime > 0 && q.EndTime > 0 {
			mquery["time"] = bson.M{"$gte": q.StartTime, "$lte": q.EndTime}
		}

		count, err := GameLogDB.Count("UserAddrLog", mquery)
		if err != nil {
			handleErr(c, 404, err.Error())
			return
		}
		logList := make([]interface{}, 0)
		err = GameLogDB.FindPageSort("UserAddrLog", q.Page-1, q.PageNum, mquery, nil, orderList, &logList)
		if err != nil {
			handleErr(c, 404, err.Error())
			return
		}

		handleOk(c, map[string]interface{}{"logList": logList, "count": count})
		return
	}

	timeOrder := -1
	if q.TimeOrder == 1 {
		timeOrder = 1
	}

	var pipeline []bson.M
	pipeline = []bson.M{
		{"$group": bson.M{"_id": "$uid"}},
		{"$count": "count"},
	}
	lst := make([]interface{}, 0)
	err := GameLogDB.PipeAll("UserAddrLog", pipeline, &lst, false)
	if err != nil {
		handleErr(c, 404, err.Error())
		return
	}
	mcount := lst[0].(bson.M)
	count := mcount["count"]

	pipeline = []bson.M{
		{"$group": bson.M{"_id": "$uid", "uid": bson.M{"$last": "$uid"}, "name": bson.M{"$last": "$name"}, "addr": bson.M{"$last": "$addr"}, "registerTime": bson.M{"$max": "$registerTime"}, "time": bson.M{"$max": "$time"}}},
		{"$sort": bson.M{"time": timeOrder}},
		{"$skip": (q.Page - 1) * q.PageNum},
		{"$limit": q.PageNum},
	}
	lst = make([]interface{}, 0)
	err = GameLogDB.PipeAll("UserAddrLog", pipeline, &lst, false)
	if err != nil {
		handleErr(c, 404, err.Error())
		return
	}

	handleOk(c, map[string]interface{}{"logList": lst, "count": count})
}
